package com.cscec.omega.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.cscec.omega.entity.APIEntity;
import com.cscec.omega.entity.ProjectEntity;
import com.cscec.omega.service.APIService;
import com.cscec.omega.utils.FileUtil;
import com.cscec.omega.utils.ResponseEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

@RestController
@RequestMapping("/api/management")
public class APIController {

    @Autowired
    private APIService apiService;

    @PostMapping("/find")
    public ResponseEntity find(@RequestBody JSONObject jsonObject){
        APIEntity apiEntity = JSON.toJavaObject(jsonObject, APIEntity.class);
//        Integer page = jsonObject.getInteger("page");
//        Integer size = jsonObject.getInteger("size");
//        Page<APIEntity> list = apiService.find(apiEntity, size, page);
        List<APIEntity> list = apiService.find(apiEntity);
        return new ResponseEntity(20000, "ok", list);
    }


    @PostMapping("/findAll")
    public ResponseEntity findAll(){
        List<APIEntity> list = apiService.findAll();
        return new ResponseEntity(20000, "ok", list);
    }

    @PostMapping("/detail")
    public ResponseEntity detail(@RequestBody JSONObject jsonObject){
        if (jsonObject==null || jsonObject.isEmpty()){
            return new ResponseEntity(-1, "id为空");
        }
        APIEntity entity = apiService.findById(jsonObject.getInteger("id"));
        return new ResponseEntity(20000, "ok", entity);
    }

    @PostMapping("/save")
    public ResponseEntity save(@RequestBody JSONObject jsonObject) {
        APIEntity apiEntity = JSON.toJavaObject(jsonObject, APIEntity.class);
        APIEntity result = apiService.save(apiEntity);
        return new ResponseEntity(20000, "ok", result);
    }

//    @PostMapping("/save")
//    public ResponseEntity save(@RequestBody APIEntity apiEntity) {
//        APIEntity result = apiService.save(apiEntity);
//        return new ResponseEntity(20000, "ok", result);
//    }

    @PostMapping("/delete")
    public ResponseEntity delete(@RequestBody JSONObject jsonObject){
        if (jsonObject==null || jsonObject.isEmpty()){
            return new ResponseEntity(-1, "id为空");
        }
        apiService.delete(jsonObject.getInteger("id"));
        return new ResponseEntity(20000, "ok");
    }

    /**
     * 下载schema
     */
    public void downLoad(String schemaName, HttpServletResponse response){
        FileUtil.downLoad(response, schemaName);
    }

}
